<template>

  <div style="width:100%; height:110%; background-color:#F2F2F2;">
    <div class="root" style="width: 80%; margin:auto; background-color:#FFFFFF; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); padding: 30px; margin-bottom: 10px;">
    <div v-if="patient">
        <h2 style="font-size: 24px; color: #333; margin-bottom: 20px;">患者信息</h2>
        <div class="info-item flex">
          <div class="field">
            <label for="realName"><strong>姓名:</strong></label>
            <input type="text" id="realName" v-model="patient.realName" disabled class="input-box" />
          </div>
          <div class="field">
            <label for="gender"><strong>性别:</strong></label>
            <input type="text" id="gender" v-model="patient.gender" disabled class="input-box" />
          </div>
          <div class="field">
            <label for="age"><strong>年龄:</strong></label>
            <input type="text" id="age" v-model="patient.age" disabled class="input-box" />
          </div>
          <div class="field">
            <label for="occupationId"><strong>职业:</strong></label>
            <input type="text" id="occupationId" v-model="patient.occupationId" disabled class="input-box" />
          </div>
          <div class="field">
            <label for="ethnicId"><strong>民族:</strong></label>
            <input type="text" id="ethnicId" v-model="patient.ethnicId" disabled class="input-box" />
          </div>
        </div>
        <div class="info-item flex">
          <div class="field" style="flex: 1; padding-right: 10px;">
            <label for="idCardNumber"><strong>证件号码:</strong></label>
            <input type="text" id="idCardNumber" v-model="patient.idCardNumber" disabled class="input-box" />
          </div>
          <div class="field" style="flex: 1; padding-right: 10px;">
            <label for="phoneNumber"><strong>手机号:</strong></label>
            <input type="text" id="phoneNumber" v-model="patient.phoneNumber" disabled class="input-box" />
          </div>
          <div class="field" style="flex: 1;">
            <label for="address"><strong>地址:</strong></label>
            <input type="text" id="address" v-model="patient.address" disabled class="input-box" />
          </div>
        </div>


      </div>
      <div v-else>
        <p style="text-align: center; color: #999;">加载中...</p>
      </div>

    </div>
    <div class="root" style="width: 80%; margin:auto; background-color:#FFFFFF; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); padding: 30px; margin-bottom: 10px;">
    <div>
      <h2 style="font-size: 24px; color: #333; margin-bottom: 20px;">体格信息</h2>
      <el-form :model="snPhysicalInfo" ref="infoRef" :inline="true" label-width="68px">
        <div>
          <el-input
              v-model="snPhysicalInfo.temperature"
              placeholder="请输入体温"
              style="margin-bottom: 10px;"
          />
          <el-input
              v-model="snPhysicalInfo.respiration"
              placeholder="请输入呼吸"
              style="margin-bottom: 10px;"
          />
          <el-input
              v-model="snPhysicalInfo.pulse"
              placeholder="请输入脉搏"
              style="margin-bottom: 10px;"
          />
          <el-input
              v-model="snPhysicalInfo.bloodPressure"
              placeholder="请输入血压"
              style="margin-bottom: 10px;"
          />
          <el-input
              v-model="snPhysicalInfo.bloodSugar"
              placeholder="请输入血糖"
              style="margin-bottom: 10px;"
          />
          <el-input
              v-model="snPhysicalInfo.bloodLipid"
              placeholder="请输入血脂"
              style="margin-bottom: 10px;"
          />
          <el-input
              v-model="snPhysicalInfo.height"
              placeholder="请输入身高"
              style="margin-bottom: 10px;"
          />
          <el-input
              v-model="snPhysicalInfo.weight"
              placeholder="请输入体重"
              style="margin-bottom: 10px;"
          />
        </div>
      </el-form>
    </div>
    </div>
    <div class="root" style="width: 80%; margin:auto; background-color:#FFFFFF; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); padding: 30px; margin-bottom: 10px;">
      <div>
        <h2 style="font-size: 24px; color: #333; margin-bottom: 20px;">诊断记录</h2>
        <el-form :model="snVisitRecord" ref="queryRef" :inline="true" label-width="68px">
          <el-form-item label="辅助检查" prop="auxiliaryExamination">
            <el-input
                v-model="snVisitRecord.auxiliaryExamination"
                placeholder="请输入辅助检查"
            />
          </el-form-item>
          <el-form-item label="初步诊断" prop="preliminaryDiagnosis">
            <el-input
                v-model="snVisitRecord.preliminaryDiagnosis"
                placeholder="请输入初步诊断"
            />
          </el-form-item>
          <el-form-item label="治疗意见" prop="treatmentAdvice">
            <el-input
                v-model="snVisitRecord.treatmentAdvice"
                placeholder="请输入治疗意见"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
                v-model="snVisitRecord.remarks"
                placeholder="请输入备注"
            />
          </el-form-item>
          <el-form-item label="医嘱" prop="medicalAdvice">
            <el-input
                v-model="snVisitRecord.medicalAdvice"
                placeholder="请输入医嘱"
            />
          </el-form-item>
          <el-form-item label="发病时间" prop="onsetTime">
            <el-input
                v-model="snVisitRecord.onsetTime"
                placeholder="请输入发病时间（YYYY-MM-DD）"
            />
          </el-form-item>
          <el-form-item label="主诉" prop="chiefComplaint">
            <el-input
                v-model="snVisitRecord.chiefComplaint"
                placeholder="请输入主诉"
            />
          </el-form-item>
        </el-form>

      </div>
    </div>
    <div class="root" style="width: 80%; margin:auto; background-color:#FFFFFF; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); padding: 30px; margin-bottom: 10px;">
      <h2 style="font-size: 24px; color: #333; margin-bottom: 20px;">处方</h2>

      <div class="container">
        <!-- 左侧：显示选中的商品和数量 -->
        <div class="left-panel">
          <h3>已选内容</h3>
          <div ref="medRef" v-for="(item, index) in selectedItems" :key="index" class="selected-item">
            <div class="item-info">
              <strong>{{ item.medicineName }}：</strong>
              <input type="number" v-model="item.medicineNum" min="1" class="medicineNum-input" />
              {{item.medicineSpecification}} -
              {{item.retailPrice}}元
            </div>
            <button @click="removeItem(index)" class="remove-btn">移除</button>
          </div>
          <div class="total-price">
            <strong>总价：{{ totalPrice }}元</strong>
          </div>
        </div>

        <!-- 右侧：商品列表 -->
        <div class="right-panel">
          <h3>商品列表</h3>
          <div v-for="(item, index) in medicineinfoList" :key="index" class="item-card">
            <div class="item-info">
              <div>{{ item.medicineName }} - {{ item.retailPrice }}元 - {{item.medicineSpecification}}</div>
            </div>
            <button @click="addItem(item)" class="add-btn">加入处方</button>
          </div>
        </div>
      </div>
      <button @click="endSub">结束就诊</button>


    </div>
    </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import Cookies from 'js-cookie';
import { addInfo } from "@/api/sn/info";
import {addRecord} from "@/api/sn/record.js";
import {listMedicineinfo} from "@/api/sn/medicineinfo.js";
const infoList = ref([]);
const TokenKey = 'Admin-Token';
const token = Cookies.get(TokenKey);
import {computed} from "vue";
import {addMedicine} from "@/api/sn/medicine.js";
// 获取路由参数
const route = useRoute();
const patientId = route.query.patientId; // 从路由的 query 中获取 patientId
console.log(patientId);
// 初始化 patient 对象
const patient = ref(null);
const loading = ref(true);
const data = reactive({
  snPhysicalInfo: {
    physicalInfoId: '',
    visitRecordId: '',
    examinationTime: '',
    temperature: '',
    respiration: '',
    pulse: '',
    bloodPressure: '',
    bloodSugar: '',
    bloodLipid: '',
    height: '',
    weight: '',
    ext1: '',
    ext2: '',
    ext3: '',
    ext4: '',
    ext5: ''
  },
  snVisitRecord: {
    visitRecordId: null,
    doctorId: null,
    patientId: null,
    visitTime: null,
    auxiliaryExamination: null,
    preliminaryDiagnosis: null,
    treatmentAdvice: null,
    remarks: null,
    medicalAdvice: null,
    diagnosisType: null,
    onsetTime: null,
    chiefComplaint: null
  },
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    medicineCategoryId: null,
    medicineStatusId: null,
    creationTime: null,
  },
  selectedItems: [
  ]
});
const { snPhysicalInfo,snVisitRecord,queryParams,selectedItems } = toRefs(data);
const infoRef = ref(null);
const queryRef = ref(null);
const medRef = ref(null);
const medicineinfoList = ref([]);
const totalPrice = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + (item.retailPrice * item.medicineNum);
  }, 0).toFixed(2);
});
function addItem(item) {
  const existingItem = this.selectedItems.find(i => i.medicineId === item.medicineId);
  if (existingItem) {
    existingItem.medicineNum += 1;  // 如果已存在，则增加数量
  } else {
    this.selectedItems.push({
      ...item,
      medicineNum: 1  // 否则新增商品并初始化数量为1
    });
  }
};
function removeItem(index) {
  this.selectedItems.splice(index, 1);  // 移除选中的商品
}
/** 查询药品信息维护列表 */
function getmedicineinfoList() {
  loading.value = true;
  queryParams.value.params = {};
  console.log(queryParams);
  listMedicineinfo(queryParams.value).then(response => {
    medicineinfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 使用 onMounted 生命周期钩子发起请求
onMounted(() => {
  if (patientId) {
    axios.get(`http://localhost:8888/sn/doctor/patient/${patientId}`, {
      headers: {
        Authorization: token
      }
    })
        .then((response) => {
          patient.value = response.data;
          console.log(response.data);  // 你可以根据需要处理返回的数据
        })
        .catch((error) => {
          console.error('获取患者信息失败:', error);
        });
  } else {
    console.error('没有找到患者ID');
  }

});
getmedicineinfoList()
/** 结束就诊按钮 */
function endSub() {
  patient._value.receptionStatus = 2;
  console.log(patient._value);
  // 使用 Axios 发送 PUT 请求
  axios.put('http://localhost:8888/sn/patient', patient._value, {
    headers: {
      'Content-Type': 'application/json',
      Authorization: token
    }
  })
      .then(response => {
        console.log('更新成功:', response.data);

        // 获取医生 ID
        axios.get('http://localhost:8888/sn/doctor/userid', {
          headers: {
            Authorization: token
          }
        })
            .then(response => {
              console.log("医生ID:", response.data);
              data.snVisitRecord.doctorId = response.data;
              data.snVisitRecord.patientId = patientId;
              console.log('Doctor ID:', data.snVisitRecord.doctorId);
              if (queryRef.value) {
                queryRef.value.validate(valid => {
                  if (valid) {
                    // 执行添加访问信息
                    addRecord(data.snVisitRecord)
                        .then(response => {
                          console.log('新增访问信息成功:', response.data);
                          // 打印响应数据，检查 visitRecordId 是否存在
                          console.log('Response data from addRecord:', response.data);
                          data.snPhysicalInfo.visitRecordId = response.data;
                          data.selectedItems.visitRecordId = response.data;

                          // 为每个药品对象添加 visitRecordId 属性
                          data.selectedItems.forEach(item => {
                            item.visitRecordId = response.data;  // 在药品对象中添加 visitRecordId
                          });

                          if (infoRef.value) {
                            infoRef.value.validate(valid => {
                              if (valid) {
                                addInfo(data.snPhysicalInfo).then(response => {
                                  alert("新增成功");
                                }).catch(error => {
                                  console.error("新增失败:", error);
                                });
                              } else {
                                console.log("表单验证失败");
                              }
                            });
                          }

                          if (medRef.value) {
                            addMedicine(data.selectedItems).then(response => {
                              console.log(selectedItems);
                              alert("新增成功");
                            }).catch(error => {
                              console.log(error);
                            })
                          }
                        })
                        .catch(error => {
                          console.error("新增访问信息失败:", error);
                        });
                  } else {
                    console.log("表单验证失败");
                  }
                });
              } else {
                console.error("Form ref is still null");
              }
            })
            .catch(error => {
              console.error('获取医生ID失败:', error);
            });
      })
      .catch(error => {
        console.error('更新失败:', error.response ? error.response.data : error.message);
      });
}







</script>
<style scoped>
.root {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

.info-item {
  margin: 15px 0;
  font-size: 16px;
  color: #555;
}

.flex {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  gap: 20px; /* 字段之间的间距 */
}

.field {
  width: 18%;  /* 控制每个输入框的宽度 */
}

label {
  display: inline-block;
  width: 80px;
  font-weight: bold;
  color: #333;
}

.input-box {
  width: 100%;
  padding: 10px;
  font-size: 16px;
  color: #555;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
  margin-left: 10px;
  box-sizing: border-box;
  cursor: not-allowed;
}

.input-box:disabled {
  background-color: #eaeaea;
}
.container {
  display: flex;
  justify-content: space-between;
}

.left-panel,
.right-panel {
  width: 48%;
}

h3 {
  font-size: 18px;
  margin-bottom: 10px;
}

.selected-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.selected-item input {
  width: 60px;
  margin-left: 10px;
  padding: 5px;
}

.item-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f9f9f9;
  margin-bottom: 10px;
  border-radius: 5px;
}

button {
  padding: 5px 10px;
  cursor: pointer;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 5px;
}

button:hover {
  background-color: #0056b3;
}
 .container {
   display: flex;
   justify-content: space-between;
   gap: 20px;
   padding: 20px;
   background-color: #f9f9f9;
 }

.left-panel, .right-panel {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h3 {
  font-size: 1.5rem;
  margin-bottom: 20px;
  color: #333;
}

.selected-item, .item-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 5px;
}

.selected-item:last-child, .item-card:last-child {
  margin-bottom: 0;
}

.item-info {
  flex-grow: 1;
}

.medicineNum-input {
  width: 60px;
  padding: 5px;
  font-size: 1rem;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.remove-btn, .add-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 8px 12px;
  font-size: 1rem;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.remove-btn:hover, .add-btn:hover {
  background-color: #0056b3;
}

.remove-btn {
  background-color: #dc3545;
}

.remove-btn:hover {
  background-color: #c82333;
}
</style>